'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  appid = `wx81b937195945b472`
  apps = `7cc1cb020a47a94b3a20e25054de498f`
  async index() {
    const { ctx } = this;
    let openid = ctx.query.openid;
    const users = await ctx.model.User.findByLogin(openid);
    ctx.status = 200
    ctx.msg = "获取成功"
    ctx.data = users;
  }
  async show() {
    const { ctx } = this;
    let code = ctx.query.code;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appid}&secret=${this.apps}&js_code=${code}&grant_type=authorization_code`
    const result = await ctx.app.curl(url, {
      dataType: 'json',
    });
    ctx.status = 200
    ctx.data = result.data
    ctx.msg = "获取成功"
  }

  async edit() {
    const { ctx } = this;
    const data = ctx.request.body;
    let basedata;
    let result;
    const users = await ctx.model.User.findByLogin(data.gender);
    if (users) {
      basedata = {
        ...users,
        userName: data.nickName,
        openid: data.openid,
        gender: data.gender,
        avatar: data.avatarUrl,
      }
      result = await ctx.model.User.update(basedata)
    } else {
      basedata = {
        userName: data.nickName,
        openid: data.openid,
        gender: data.gender,
        avatar: data.avatarUrl,
      }
      result = await ctx.model.User.create(basedata)

    }


    ctx.status = 200
    ctx.data = result
    ctx.msg = "获取成功"


  }


}

module.exports = HomeController;
